#
# OpenLookup - main.py
#
# Copyright 2008 Ken Rimey
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

welcome = '''<html>
<head>
  <title>OpenLookup V1</title>
  <style type="text/css">
    body { margin-top: 1em; margin-bottom: 1em;
           margin-left: 1em; margin-right:  1em; }
  </style>
</head>

<body>
  <h2>OpenLookup V1</h2>

  <p>This is a centralized key-value datastore
  compatible with <a href="http://opendht.org/">OpenDHT</a>.</p>

  <p>The XML-RPC interface is at
  <a href="http://openlookup.appspot.com/">http://openlookup.appspot.com/</a>
  (on port 80).</p>

  <p>The <a href="http://openlookup.googlecode.com/">source code</a>
  is available.  This is OpenLookup v1, hosted on
  <a href="http://code.google.com/appengine/">Google App Engine</a>.</p>

  <address>
    <a href="mailto:rimey@hiit.fi">Ken Rimey</a>
  </address>
</body>
</html>
'''

import wsgiref.handlers
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher

from google.appengine.ext import webapp

from opendht import OpenDHT

xmlrpc_handler = SimpleXMLRPCDispatcher(allow_none=False, encoding=None)
xmlrpc_handler.register_instance(OpenDHT())

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(welcome)

    def post(self):
        response_text = xmlrpc_handler._marshaled_dispatch(self.request.body)
        self.response.headers['Content-Type'] = 'text/xml'
        self.response.out.write(response_text)

def main():
    application = webapp.WSGIApplication([('/', MainPage)],
                                         debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
